package com.css.fxfzdzzh.modules.drill.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.modules.basicData.vo.JcClimate;
import com.css.fxfzdzzh.modules.drill.param.JcRfcpY02Param;
import com.css.fxfzdzzh.modules.drill.service.DrillService;
import com.css.fxfzdzzh.modules.drill.vo.*;
import com.css.fxfzdzzh.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: fxfzdzzh
 * @Author: lhl
 * @CreateDate: 2023/2/14 15:17
 */
@Service
public class DrillServiceImpl implements DrillService {

    @Value("${basicData.url}")
    public String basicDataUrl;

    @Resource(name="httpsRestTemplates")
    RestTemplate restTemplate;

    @Value("${hypergraph.iServerHttp}")
    String iServerHttp;

    @Override
    public RestResponse page(JcRfcpY02Param param) {
        String url = basicDataUrl + "/datacenter/jcRfcpY02/page?param=" + param;
        RestResponse jcsjPage = getJCSJ(url, 1);
        return jcsjPage;
    }

    @Override
    public RestResponse findAllById(String drillId) {
        String url = basicDataUrl + "/datacenter/jcRfcpY02/findAllById/" + drillId;
        return getJCSJ(url, 2);
    }

    /*@Override
    public void dataExport(HttpServletResponse response, JcRfcpY02Param param) {
        BufferedInputStream inputStream = null;
        try {
            param.setPage(null);
            param.setRows(null);
            String url1 = basicDataUrl + "/datacenter/jcRfcpY02/page?param=" + param;
            JSONArray jsonArray = (JSONArray) ((JSONObject) getJCSJ(url1, 1).getData()).get("list");

            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String zipName = dateStr + "Excel压缩包导出.zip";
            response.setContentType("application/octet-stream");
            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String(zipName.getBytes("GB2312"), "ISO8859-1"));
            response.setCharacterEncoding("UTF-8");
            OutputStream out = response.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(out);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            //D:\zfzx\fxfzdzzh\src\main\resources\template\钻孔资料收集_标准数据格式模板.xlsx
            ClassPathResource classPathResource = new ClassPathResource("\\template\\钻孔资料收集_标准数据格式模板.xlsx");
            //String path ="/usr/zhaoshuai/dzzh/template/钻孔资料收集_标准数据格式模板.xlsx";
            //String filePath = URLDecoder.decode(path, "utf-8");

            File file = classPathResource.getFile();
            //File file = new File(filePath);
            if (file.exists()) {
                inputStream = new BufferedInputStream(new FileInputStream(file));
                // POIFSFileSystem fs = new POIFSFileSystem(inputStream);

                for (int y = 0; y < jsonArray.size(); y++) {
                    JSONObject jsonObject2 = jsonArray.getJSONObject(y);
                    String drillId = jsonObject2.getString("id");
                    String url2 = basicDataUrl + "/datacenter/jcRfcpY02/findAllById/" + drillId;
                    JSONObject jsonObject = (JSONObject) getJCSJ(url2, 2).getData();

                    XSSFWorkbook workbook = new XSSFWorkbook(inputStream);// 创建一个Excel文件
                    XSSFDataFormat dataFormat = workbook.createDataFormat(); //设置格式
                    // 全局样式设置
                    XSSFCellStyle allStyle = workbook.createCellStyle();
                    allStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
                    allStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());// 填充白色
                    allStyle.setBorderBottom(BorderStyle.THIN); // 下边框
                    allStyle.setBorderLeft(BorderStyle.THIN);// 左边框
                    allStyle.setBorderTop(BorderStyle.THIN);// 上边框
                    allStyle.setBorderRight(BorderStyle.THIN);// 右边框
                    allStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
                    allStyle.setWrapText(true);//自动换行

                    //处理日期格式
                    XSSFCellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setBorderBottom(BorderStyle.THIN); // 下边框
                    dateStyle.setBorderLeft(BorderStyle.THIN);// 左边框
                    dateStyle.setBorderTop(BorderStyle.THIN);// 上边框
                    dateStyle.setBorderRight(BorderStyle.THIN);// 右边框
                    dateStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
                    dateStyle.setWrapText(true);//自动换行
                    dateStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); //设置日期格式

                    //Y01单孔标准化数据总览
                    XSSFSheet sheet1 = workbook.getSheet("Y01单孔标准化数据总览");

                    JcRfcpFileExcelVO jcRfcpFileExcelVO = (JcRfcpFileExcelVO) PlatformBeanUtils.copyProperties(jsonObject.getJSONObject("0"), JcRfcpFileExcelVO.class);
                    String[][] strings1_1 = PoiExcelUtil.objectChangeArrays(jcRfcpFileExcelVO, 2);
                    for (int i = 2; i < strings1_1.length + 2; i++) {
                        XSSFRow row0 = sheet1.getRow(i);
                        row0.setHeightInPoints(30);
                        for (int j = 3; j < 5; j++) {
                            XSSFCell cel0_1 = row0.getCell(j);
                            if (j == 3) {
                                cel0_1.setCellValue(new XSSFRichTextString(strings1_1[i - 2][0]));
                            } else {
                                if ("1".equals(strings1_1[i - 2][0])) {
                                    cel0_1.setCellValue(new XSSFRichTextString(strings1_1[i - 2][1]));
                                }
                            }
                            cel0_1.setCellStyle(allStyle);
                        }
                        sheet1.autoSizeColumn((short) i);
                    }

                    JcRfcpDrillDatafileExcelVO jcRfcpDrillDatafileExcelVO = (JcRfcpDrillDatafileExcelVO) PlatformBeanUtils.copyProperties(jsonObject.getJSONObject("1"),
                            JcRfcpDrillDatafileExcelVO.class);
                    String[][] strings1_2 = PoiExcelUtil.objectChangeArrays(jcRfcpDrillDatafileExcelVO, 2);
                    for (int i = 2; i < strings1_2.length + 2; i++) {
                        XSSFRow row0 = sheet1.getRow(i + 12);
                        row0.setHeightInPoints(30);
                        for (int j = 3; j < 5; j++) {
                            XSSFCell cel0_1 = row0.getCell(j);
                            if (j == 3) {
                                cel0_1.setCellValue(new XSSFRichTextString(strings1_2[i - 2][0]));
                            } else {
                                if ("1".equals(strings1_2[i - 2][0])) {
                                    cel0_1.setCellValue(new XSSFRichTextString(strings1_2[i - 2][1]));
                                }
                            }
                            cel0_1.setCellStyle(allStyle);
                        }
                        sheet1.autoSizeColumn((short) i);
                    }

                    // 创建Y02成孔信息Sheet
                    XSSFSheet sheet2 = workbook.getSheet("Y02成孔信息");
                    // JcRfcpY02 jcRfcpY02 = this.findById(drillId);
                    JcRfcpY02ExcelVO jcRfcpY02ExcelVO = (JcRfcpY02ExcelVO) PlatformBeanUtils.copyProperties(jsonObject2,
                            JcRfcpY02ExcelVO.class);
                    String[] strings2 = PoiExcelUtil.objectChangeArray(jcRfcpY02ExcelVO);
                    for (int i = 0; i < 24; i++) {
                        XSSFRow row0 = sheet2.getRow(i);
                        row0.setHeightInPoints(30);
                        XSSFCell celi_2 = row0.getCell(1);
                        celi_2.setCellValue(strings2[i]);
                        if (i == 3 || i == 7 || i == 8) {
                            celi_2.setCellStyle(dateStyle);
                        } else {
                            celi_2.setCellStyle(allStyle);
                        }
                        sheet1.autoSizeColumn((short) i);
                    }

                    //Y04sheet
                    XSSFSheet sheet4 = workbook.getSheet("Y04地层岩性分层");
                    JSONArray excelVOS4 = (JSONArray) jsonObject.get("4");
                    for (int k = 1; k <= excelVOS4.size(); k++) {
                        JcRfcpY04ExcelVO jcRfcpY04ExcelVO = (JcRfcpY04ExcelVO) PlatformBeanUtils.copyProperties(excelVOS4.getJSONObject(k - 1),
                                JcRfcpY04ExcelVO.class);
                        String[] y04Values = PoiExcelUtil.objectChangeArray(jcRfcpY04ExcelVO);

                        XSSFRow rowk = sheet4.createRow(k);
                        rowk.setHeightInPoints(30);
                        for (int i = 0; i < 8; i++) {
                            XSSFCell celk_i = rowk.createCell(i);
                            celk_i.setCellValue(new XSSFRichTextString(y04Values[i]));
                            celk_i.setCellStyle(allStyle);
                        }
                        sheet4.autoSizeColumn(k);
                    }

                    //Y05sheet
                    XSSFSheet sheet5 = workbook.getSheet("Y05标贯值");
                    JSONArray excelVOS5 = (JSONArray) jsonObject.get("5");
                    for (int k = 1; k <= excelVOS5.size(); k++) {
                        JcRfcpY05ExcelVO jcRfcpY05ExcelVO = (JcRfcpY05ExcelVO) PlatformBeanUtils.copyProperties(excelVOS5.getJSONObject(k - 1),
                                JcRfcpY05ExcelVO.class);
                        String[] y05Values = PoiExcelUtil.objectChangeArray(jcRfcpY05ExcelVO);

                        XSSFRow rowk = sheet5.createRow(k);
                        rowk.setHeightInPoints(30);
                        for (int i = 0; i < 3; i++) {
                            XSSFCell celk_i = rowk.createCell(i);
                            celk_i.setCellValue(new XSSFRichTextString(y05Values[i]));
                            celk_i.setCellStyle(allStyle);
                        }
                        sheet5.autoSizeColumn((short) k);
                    }

                    //Y06sheet
                    XSSFSheet sheet6 = workbook.getSheet("Y06剪切波实测值");
                    JSONArray excelVOS6 = (JSONArray) jsonObject.get("6");
                    for (int k = 1; k <= excelVOS6.size(); k++) {
                        JcRfcpY06ExcelVO jcRfcpY06ExcelVO = (JcRfcpY06ExcelVO) PlatformBeanUtils.copyProperties(excelVOS6.getJSONObject(k - 1),
                                JcRfcpY06ExcelVO.class);
                        String[] y06Values = PoiExcelUtil.objectChangeArray(jcRfcpY06ExcelVO);

                        XSSFRow rowk = sheet6.createRow(k);
                        rowk.setHeightInPoints(30);
                        for (int i = 0; i < 5; i++) {
                            XSSFCell celk_i = rowk.createCell(i);
                            celk_i.setCellValue(new XSSFRichTextString(y06Values[i]));
                            celk_i.setCellStyle(allStyle);
                        }
                        sheet6.autoSizeColumn((short) k);
                    }

                    // Y10sheet
                    XSSFSheet sheet10 = workbook.getSheet("Y10土工试验参数");
                    JSONArray excelVOS10 = (JSONArray) jsonObject.get("10");
                    for (int k = 4; k < excelVOS10.size() + 4; k++) {
                        JcRfcpY10ExcelVO jcRfcpY10ExcelVO = (JcRfcpY10ExcelVO) PlatformBeanUtils.copyProperties(excelVOS10.getJSONObject(k - 4),
                                JcRfcpY10ExcelVO.class);
                        String[] values = PoiExcelUtil.objectChangeArray(jcRfcpY10ExcelVO);

                        XSSFRow rowk = sheet10.createRow(k);
                        rowk.setHeightInPoints(30);
                        for (int i = 0; i < 32; i++) {
                            XSSFCell celk_i = rowk.createCell(i);
                            celk_i.setCellValue(new XSSFRichTextString(values[i]));
                            celk_i.setCellStyle(allStyle);
                        }
                        sheet10.autoSizeColumn(k);
                    }
                    workbook.write(bos);
                }
                String fileName = "钻孔资料收集" + System.currentTimeMillis() + ".xls";
                ZipEntry entry = new ZipEntry(fileName);
                zos.putNextEntry(entry);

                bos.writeTo(zos);
                zos.closeEntry();
            }

            zos.flush();
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/

    @Override
    public void dataExportNew(HttpServletResponse response, JcRfcpY02Param param) throws IOException{
        //通过条件获取导出数据
        String url = basicDataUrl + "/datacenter/jcClimate/getByArea?1=1&province=" + param.getProvince()
                + "&city=" + param.getCity() + "&county=null";
        RestResponse jcsj = getJCSJ(url, 5);
        JSONObject data= (JSONObject) jcsj.getData();
        List<JcClimate> list = JSON.parseArray(JSON.toJSONString(data.get("data")), JcClimate.class);
        System.out.println(list.size());
        EasyPoiExcelUtil.exportExcel(list, "气候", "sheet1", JcClimate.class, "气候", response);
    }

    @Override
    public void drillExport(HttpServletResponse response, JcRfcpY02Param param) {
        //通过条件获取导出数据
        String url = basicDataUrl + "/datacenter/jcRfcpY02/page?param=" + param;
        RestResponse jcsjPage = getJCSJ(url, 1);
        JSONObject data= (JSONObject) jcsjPage.getData();
        List<JcClimate> list = JSON.parseArray(JSON.toJSONString(data.get("data")), JcClimate.class);
        System.out.println(list.size());
        EasyPoiExcelUtil.exportExcel(list, "钻孔", "sheet1", JcClimate.class, "钻孔", response);
    }

    @Override
    public RestResponse getJCSJ(String url, int tab) {
        MultiValueMap<String, Object> valueMap = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzdzzh");
        headers.set("subsystemCode", "dzdzzhpg");
        HttpEntity<MultiValueMap> r = new HttpEntity<>(valueMap, headers);
        RestResponse resp = null;
        try {
            if (tab == 1) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 2) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 3) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 4) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            }else if (tab == 5){
                ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class);
                resp = RestResponse.succeed(exchange.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    @Override
    public RestResponse getDataByDzzhTifFile(String layerName) {
//        String dataUrl = "http://10.7.209.199:8090/iserver/services/data-dzzhTifFile/rest/data/datasources/dzzhTifFile/datasets/" + layerName + ".rjson";
        String dataUrl = iServerHttp + "/iserver/services/data-dzzhTifFile/rest/data/datasources/dzzhTifFile/datasets/" + layerName + ".rjson";
        try {
            dataUrl = URLDecoder.decode(dataUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        dataUrl = dataUrl.replaceAll("%3A", ":").replaceAll("%2F", "/").replaceAll("\\+", "%20");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> r = new HttpEntity<>(headers);
        String statusCodeValue = null;
        JSONObject jsonObject = null;
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(dataUrl, HttpMethod.GET, r, String.class);
            jsonObject = JSON.parseObject(JSON.toJSONString(exchange));
            statusCodeValue = jsonObject.getString("statusCodeValue");
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.fail(e.getMessage());
        }
        if (!"200".equals(statusCodeValue)){
            return RestResponse.fail(500,"此版本下没有数据");
        }
        String body = JSON.toJSONString(jsonObject.getString("body"));
        Object s = JSON.parse(body);
        Map jsonMap = JSON.parseObject((String) s);
        Map<String, Object> map = (Map<String, Object>) jsonMap.get("datasetInfo");
        BigDecimal max = (BigDecimal) map.get("maxValue");
        if (max == null) {
            return RestResponse.fail(500,"此版本下没有数据");
        }
        return RestResponse.succeed();
    }

    @Override
    public RestResponse getJCSJ(String url, int tab, JSONObject valueMap) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "fxfzdzzh");
        headers.set("subsystemCode", "dzdzzhpg");
        HttpEntity<JSONObject> r = new HttpEntity<>(valueMap, headers);
        RestResponse resp = null;
        try {
            if (tab == 1) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 2) {
                JSONObject data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONObject("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 3) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 4) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONArray("data");
                resp = RestResponse.succeed(data);
            } else if (tab == 5) {
                JSONArray data = restTemplate.exchange(url, HttpMethod.POST, r, JSONObject.class).getBody().getJSONObject("data").getJSONArray("data");
                resp = RestResponse.succeed(data);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

}
